19-apis

Author
Affiliation

Prof Emily Kurtz

Carleton College
Stat 220 - Spring 2026

TidyCensus

Install tidycensus

install.packages("tidycensus")
library(tidycensus)
library(tidyverse)

Example call:

acs_mn_2020 <- tidycensus::get_acs(
    year = 2020,
    state = "MN",
    geography = "county",
    variables = c("B01003_001", "B19013_001"),
    output = "wide",
    geometry = TRUE
)

Storing your API key

  1. Create a new text file in the same folder as your .rmd
  2. Copy and paste your census key into the empty file
  3. Save the file as census_api_key.txt
my_key <- readLines("census_api_key.txt")

and tell tidycensus what your API key is with:

census_api_key(my_key)

Do not commit and push census_api_key.txt to github

httr2

Install if not already installed:

install.packages("httr2")
library(httr2)

Example call

hmong_state_request <- request("https://api.census.gov/data") %>% 
    req_url_path_append("2019") %>% 
    req_url_path_append("acs") %>% 
    req_url_path_append("acs1") %>% 
    req_url_query(get = c("NAME", "B02015_009E", "B02015_009M"), `for` = I("state:*"), key = census_api_key, .multi = "comma")
hmong_state_response <- req_perform(hmong_state_request)
hmong_state_tbl <- hmong_state_response %>%
  resp_body_json(simplifyVector = TRUE) %>%
  janitor::row_to_names(1) %>%
  as_tibble()

hmong_state_tbl

Your Turn

  • Edit the httr code to access a new variable of your choice
  • Make a httr request to access the 1-year ACS data from 2018, 2019, 2021, and 2022. Make sure to save your results from each call!
  • Combine all years into a single dataset
  • Make a time series plot with your chosen variable on the y-axis, year on the x-axis, colored by state.
    • You may want to first filter to only a few states
    • You will need to do some cleaning of the data